package Network

import (
	"SQL/db"
	"logs"
	"strconv"
)

type member struct {
	MemberID   string
	MemberIcon string
	IsManager  bool
}

func getGroupMember(clientID string, args interface{}) (response *ServerResponse) {
	code := Success
	msg := ""
	var res interface{}
	defer func() {
		if code != Success {
			logs.Print("code: ", code, " msg: ", msg)
		}
		response = &ServerResponse{
			Method:  "/getGroupMember",
			Code:    code,
			Message: msg,
			Result:  res,
		}
	}()
	argsname := []string{"groupID", "pageIndex", "pageSize"}
	msg, code, argsmap := initargs(args, argsname)
	if code != Success {
		return
	}
	groupID, _ := strconv.Atoi(argsmap["groupID"].(string))
	pageIndex, _ := strconv.Atoi(argsmap["pageIndex"].(string))
	pageSize, _ := strconv.Atoi(argsmap["pageSize"].(string))
	sql := "select *from groups where id =$1"
	rows, err := db.RowQuery(sql, groupID)
	if err != nil {
		logs.Print(err.Error())
		msg = err.Error()
		code = errDBQueryFailed
		return
	}
	defer rows.Close()
	if rows.Next() == false {
		msg = mNotExistGroupID
		code = errGroupIDNotExist
		return
	}
	sql = `select o.id,o.iconurl,m.ismanager 
			from objects o,members m 
			where m.groupid=$1 and m.userid=o.id
			order by id asc limit $2 offset $3`
	offset := pageIndex * pageSize
	var objs []interface{}
	objs = append(objs, groupID, pageSize, offset)
	rows, err = db.RowQuery(sql, objs...)
	if err != nil {
		logs.Print(err.Error())
		msg = err.Error()
		code = errDBQueryFailed
		return
	}
	defer rows.Close()
	if err != nil {
		logs.Print("GroupList Query error", err.Error())
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	members := make([]member, 0)
	var count int
	for rows.Next() {
		count++
		var memberid string
		var membericon string
		var ismanager bool
		err = rows.Scan(&memberid, &membericon, &ismanager)
		if err != nil {
			logs.Print("GroupMember rows.Scan error", err.Error())
		}
		tem := &member{MemberID: memberid, MemberIcon: membericon, IsManager: ismanager}
		members = append(members, *tem)
	}
	if count == 0 {
		msg = "该页已经没有数据了"
		return
	}
	res = members
	msg = "获取群成员成功"
	return
}
